/**
 * Lockbox
 * a Password and Secret Information Manager
 * Options view
 *
 * Created by Nathan Black
 * 
 * Licensed under GPL v2
 */
 
#import "LockboxOptionsView.h"
#import "LockboxOptions.h"
#import "LockboxApp.h"

@interface LockboxOptionsView (Private)

- (void)returnFromOptionsView;
- (void)changePassword;
- (void)filtersUpdated;
- (void)switchEvent;
- (id)changePwCell;
- (void)changePwButtonPressed;
- (UIPreferencesControlTableCell*)createSwitchCellWithTitle:(NSString*)title frame:(struct CGRect)frame;

@end


@implementation LockboxOptionsView

- (void)dealloc
{
    [_filterCell release];
    [_showSecretCell release];
    [_selectEditCell release];
    [_importCell release];
    [_changePwGroupCell release];
    [_listViewGroupCell release];
    [_importViewGroupCell release];

    [super dealloc];
}

- (id)initWithFrame:(struct CGRect)frame app:(id)app tagDelegate:(id)tagDelegate
{
    if ((self = [super initWithFrame:frame app:app tagDelegate:tagDelegate]))
    {
        _filterCell = [self createSwitchCellWithTitle:@"Tag Filter" frame:frame];
        _showSecretCell = [self createSwitchCellWithTitle:@"Show Password/Secret" frame:frame];
        _selectEditCell = [self createSwitchCellWithTitle:@"Select to Edit" frame:frame];
        _importCell = [[UIPreferencesTableCell alloc] init];
        [_importCell setValue:@"Import CSV File"];
        [_importCell setShowDisclosure:YES];

        _changePwGroupCell = [[UIPreferencesTableCell alloc] init];
        _listViewGroupCell = [[UIPreferencesTableCell alloc] init];
        [_listViewGroupCell setTitle: @"List View Options"];
        _importViewGroupCell = [[UIPreferencesTableCell alloc] init];
        

        _editRowBase = 2;
    }
    return self;
}

-(void)switchEvent
{
    _dirty = true;
}

- (UIPreferencesControlTableCell*)createSwitchCellWithTitle:(NSString*)title frame:(struct CGRect)frame
{
    CGRect switchRect = CGRectMake(frame.size.width - 114.0f, 9.0f, 96.0f, 32.0f);

    UIPreferencesControlTableCell* swCell = [[[UIPreferencesControlTableCell alloc] init] retain];
    [swCell setValue:title];
    UISwitchControl* sw = [[UISwitchControl alloc] initWithFrame: switchRect];
    [sw addTarget:self action:@selector(switchEvent) forEvents:-1 /* everything TODO: just a switchchanged event would be nice */];
    [swCell setControl:sw];
    return swCell;
}

-(void)refresh
{
    LockboxOptions* opts = [LockboxOptions globalInstance];
    [super setTags:[opts tagFilters]];
    [((UISwitchControl*)[_filterCell control]) setValue:[opts tagFilterOn]];
    [((UISwitchControl*)[_showSecretCell control]) setValue:[opts showSecretInList]];
    [((UISwitchControl*)[_selectEditCell control]) setValue:[opts selectToEdit]];
}

- (void)saveOptions
{
    LockboxOptions* opts = [LockboxOptions globalInstance];
    [opts setTagFilters:[super saveTags]];
    [opts setTagFilterOn:[((UISwitchControl*)[_filterCell control]) value]];
    [opts setShowSecretInList:[((UISwitchControl*)[_showSecretCell control]) value]];
    [opts setSelectToEdit:[((UISwitchControl*)[_selectEditCell control]) value]];
    [opts save];
}

- (void)exitView 
{
    if (_transDelegate != nil && [_transDelegate respondsToSelector:@selector(returnFromOptionsView)]) {
        [_transDelegate returnFromOptionsView];
        [_prefsTable stopEditing];
    }
    
    if (_dirty) {
        [self saveOptions];
        
        if (_tagDelegate != nil && [_tagDelegate respondsToSelector:@selector(filtersUpdated)]) {
            [_tagDelegate filtersUpdated];
        }
    }
}

- (void)setNavBarButtons:(BOOL)editing
{
    // TODO: Need to add the ability for tags to be added to persist for the duration of the process instance, 
    // otherwise editing functionality works fine.
    [_navBar showLeftButton:@"Back" withStyle:2 rightButton:NULL withStyle:3];
}

- (void)changePwButtonPressed
{
   NSLog(@"changePwButtonPressed");
    if (_transDelegate != nil && [_transDelegate respondsToSelector:@selector(changePassword)]) {
        [_transDelegate changePassword];
        [_prefsTable stopEditing];
    }
}

- (id)changePwCell
{
    if (_changePwCell == NULL) {
        NSLog(@"allocating deleteCell");
        CGRect chngPwFrame = [_prefsTable frameOfPreferencesCellAtRow:0 inGroup:0];
        chngPwFrame.origin.y += 15.0f;
        _changePwCell = [[UIPreferencesDeleteTableCell alloc] initWithFrame:chngPwFrame];
        [[_changePwCell button] setTitle:@"Change Password"];
        [[_changePwCell button] addTarget:self action:@selector(changePwButtonPressed) forEvents:0x40 /*kGSEventTypeButtonSelected or mouseUp*/];
        struct CGRect bounds = [[_changePwCell control] bounds];
        NSLog(@"Delete Cell control bounds left: %3.3f top: %3.3f x: %3.3f, height: %3.3f", bounds.origin.x, bounds.origin.y, bounds.size.width, bounds.size.height);
        
        /*_changePwCell = [[UIPreferencesControlTableCell alloc] initWithFrame:chngPwFrame];
        chngPwFrame.origin.x = chngPwFrame.origin.y = 0.0f;
        UIPushButton* button = [[[UIPushButton alloc] initWithFrame:chngPwFrame] autorelease];
        [button setTitle:@"Change Password"];
        [button addTarget:self action:@selector(changePwButtonPressed) forEvents:0x40];
        //[_changePwCell setControl:button];
        [_changePwCell addSubview:button];*/
        
    }
    return _changePwCell;
}

- (BOOL)canSelectRow:(int)row
{
    return (row >= _editRowBase);
}

/**
 * Select a new row.
 */
- (void)tableRowSelected:(NSNotification *)notification {

    NSLog(@"OptionsView tableRowSelected: selected=%d tags=%d", 
        [_prefsTable selectedRow], [self getTagCount]);
        
    if ([_prefsTable selectedRow] == ([self getTagCount]+6)) {
        [_prefsTable selectRow: -1 byExtendingSelection: NO withFade: YES];
        // show import view
        [_transDelegate transitionToView:[_transDelegate getImportView] withTransition:1];
    }
    else {
        [super tableRowSelected:notification];
    }
}


- (int) numberOfGroupsInPreferencesTable: (UIPreferencesTable*)table 
{
    NSLog(@"OptionsView numberOfGroupsInPreferencesTable");
    return 4;
}

- (int) preferencesTable: (UIPreferencesTable*)table numberOfRowsInGroup: (int)group 
{
    NSLog(@"OptionsView numberOfRowsInGroup: %d", group);
    switch (group) {
        case 0: return [super preferencesTable:table numberOfRowsInGroup:group] + 1;
        case 1: return 2;
        case 2: return 1;
        case 3: return 1;
    }

};

- (UIPreferencesTableCell*) preferencesTable: (UIPreferencesTable*)table cellForGroup: (int)group 
{
    NSLog(@"OptionsView cellForGroup: %d", group);
    switch (group) {
        case 0: return [super preferencesTable:table cellForGroup:group];
        case 1: return _listViewGroupCell;
        case 2: return _importViewGroupCell;
        case 3: return _changePwGroupCell;
    }
}

- (UIPreferencesTableCell*) preferencesTable: (UIPreferencesTable*)table cellForRow: (int)row inGroup: (int)group 
{
    NSLog(@"OptionsView cellForRow: %d inGroup: %d", row, group);

    if (group == _tagGroup) {
        if (row == 0) {
            return _filterCell;
        }
        else {
            return [super preferencesTable:table cellForRow:row inGroup:group];
        }
    }
    else if (group == 1) {
        switch (row) {
            case 0: return _showSecretCell;
            case 1: return _selectEditCell;
            default: return NULL;
        }
    }
    else if (group == 2 && row == 0) {
        return _importCell;
    }
    else if (group == 3 && row == 0) {
        return [self changePwCell];
    }
    else  {
        //NSAssert(false, @"OptionsView cellForRow: request out of range");
        return NULL;
    }
}

- (float) preferencesTable: (UIPreferencesTable*)table heightForRow: (int)row inGroup: (int)group withProposedHeight: (float)proposed 
{
    if (group == 1 && row == -1) return proposed * 1.5;

    return [super preferencesTable:table heightForRow:row inGroup:group withProposedHeight:proposed];
}

@end
